/*
 * @Author: 悦者生存 1002783067@qq.com
 * @Date: 2023-03-11 11:03:33
 * @LastEditors: 悦者生存 1002783067@qq.com
 * @LastEditTime: 2023-04-13 20:48:38
 * @FilePath: /koa2-ts-template/src/middlewares/view.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import koa from 'koa';
import path from 'path';
import fs from 'fs-extra';

export const view = (dirPath: string) => {
  return async (ctx: koa.Context, next: Function) => {
    // 在ctx上挂载render函数
    ctx.render = async (filename: string) => {
      const filePath = path.join(dirPath, filename);
      const template = await fs.readFile(filePath + '.html');
      ctx.body = template.toString();
    };
    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    await next();
  };
};
